package com.dycong.common.IO.socket.SSL.ssl;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.IOException;
import java.net.InetSocketAddress;

/**
 * Created by dycong on 2017/3/28.
 */
public class Client {
    private String HOST = "172.0.0.1";
    private int PORT = 12121;
    private SSLContext sslContext = null;
    private SSLSocket socket;

    public Client() {
    }

    public Client(String host, int port) {
        HOST = host;
        PORT = port;
    }

    public void start() {
        try {
            sslContext = ClientAuth.getSslContext();
            SSLSocketFactory socketFactory = (SSLSocketFactory) sslContext.getSocketFactory();
            socket = (SSLSocket) socketFactory.createSocket();
            String[] pwdsuits = socket.getSupportedCipherSuites();
            //socket可以使用所有支持的加密套件
            socket.setEnabledCipherSuites(pwdsuits);
            //默认就是true
            socket.setUseClientMode(true);

            //关闭socket时，立即释放socket绑定端口以便端口重用，默认为false
            socket.setReuseAddress(true);
            //关闭传输缓存，默认为false
            socket.setTcpNoDelay(true);
            //如果输入流等待1000毫秒还未获得服务端发送数据，则提示超时，0为永不超时
            socket.setSoTimeout(10000);
            //关闭socket时，底层socket不会直接关闭，会延迟一会，直到发送完所有数据
            //等待10秒再关闭底层socket连接，0为立即关闭底层socket连接
            socket.setSoLinger(true, 10);
            //设置性能参数，可设置任意整数，数值越大，相应的参数重要性越高（连接时间，延迟，带宽）
            socket.setPerformancePreferences(3, 2, 1);

            socket.connect(new InetSocketAddress(HOST, PORT));

            //hand shake compete
            MyHandshakeCompletedListener myHandshakeCompletedListener = new MyHandshakeCompletedListener();
            socket.addHandshakeCompletedListener(myHandshakeCompletedListener);
        } catch (Exception e) {

        } finally {
            try {
                if (socket!=null)
                socket.close();
            } catch (IOException e) {

            }
        }
    }

}
